package ar.com.jsejtman.cajugastos2.security.controller;

import ar.com.jsejtman.cajugastos2.security.dto.PasswordResetDto;
import ar.com.jsejtman.common.mail.exception.CannotSendEmailException;
import ar.com.jsejtman.common.security.credential.exception.InvalidUsernameException;
import ar.com.jsejtman.common.security.credential.exception.UsernameNotMatchingEmailAddressException;
import ar.com.jsejtman.common.security.credential.service.ISecurityCredentialService;
import ar.com.jsejtman.common.service.exception.EntityRetrievalException;
import ar.com.jsejtman.common.service.exception.EntitySavingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Realiza operaciones vinculadas con el inicio de sesión.
 * 
 * @author jsejtman
 */
@Controller
public class LoginController {

	/**
	 * Logger del controller.
	 */
	private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);

	/**
	 * Servicio de credenciales de seguridad.
	 */
	@Autowired
	private ISecurityCredentialService securityCredentialService;

	/**
	 * Remite automáticamente a la página de inicio de sesión.
	 * 
	 * @return un string con una definicion de tiles a la cual dirigirse
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	protected final ModelAndView goToLoginPage() {

		return (new ModelAndView("login"));
	}

	/**
	 * Procesa una solicitud de reinicio de clave.
	 * 
	 * @param passwordResetDto Formulario de reinicio de clave.
	 * @param model Modelo de la vista.
	 * @return ModelAndView Modelo y vista.
	 */
	@RequestMapping(value = "/passwordResetRequest", method = RequestMethod.POST)
	public final ModelAndView processPasswordResetRequest(
	        @ModelAttribute("passwordResetForm") final PasswordResetDto passwordResetDto,
	        final ModelMap model) {

		LoginController.LOG.debug("Solicitud de reinicio de clave para "
		        + passwordResetDto.getPasswordResetUsername() + " con Email "
		        + passwordResetDto.getPasswordResetEmailAddress() + " recibida.");

		try {
			this.securityCredentialService.resetUserPassword(
			        passwordResetDto.getPasswordResetUsername(),
			        passwordResetDto.getPasswordResetEmailAddress());
			
			model.put("successful_password_reset_key", "message.successfulPasswordReset");
			
		} catch (final CannotSendEmailException e) {
			model.put("password_reset_error_key", "message.cannotSendEmail");
			model.put("additional_error_details", e.getMessage());
		} catch (final EntityRetrievalException e) {
			model.put("password_reset_error_key", "message.errorWhileResettingPassword");
			model.put("additional_error_details", e.getMessage());
		} catch (final EntitySavingException e) {
			model.put("password_reset_error_key", "message.errorWhileResettingPassword");
			model.put("additional_error_details", e.getMessage());
		} catch (final InvalidUsernameException e) {
			model.put("password_reset_error_key", "message.invalidUsername");
			model.put("additional_error_details", e.getMessage());
		} catch (final UsernameNotMatchingEmailAddressException e) {
			model.put("password_reset_error_key", "message.usernameAndEmailAddressNotMatching");
			model.put("additional_error_details", e.getMessage());
		}
		
		return (new ModelAndView("login", model));
	}
}
